package com.hydra.auth.controller;

import com.alibaba.fastjson2.JSONObject;
import com.hydra.auth.dto.ModifyPassDto;
import com.hydra.auth.entity.SysUser;
import com.hydra.auth.service.AuthService;
import com.hydra.auth.service.LoginService;
import com.hydra.auth.service.ValidateCodeService;
import com.hydra.auth.service.impl.MailValidateCodeServiceImpl;
import com.hydra.base.common.BaseConstant;
import com.hydra.base.dto.auth.AuthUser;
import com.hydra.base.error.BusinessException;
import com.hydra.base.redis.RedisPlugin;
import com.hydra.base.resp.BaseResult;
import com.hydra.base.utils.JsonUtil;
import com.hydra.base.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.hydra.auth.common.AuthConstant.RegisterConstant.VALIDATE_CODE_TYPE_FORGET_PASSWORD;

/**
 * 登录验证的控制器
 * @Author Hydra
 * @Date 2022/4/18 11:09
 */
@Slf4j
@RequestMapping("/api/auth/")
@RestController
public class AuthController {

    @Resource
    private RedisPlugin redisPlugin;

    @Resource
    private AuthService authService;

    @Resource
    private LoginService loginService;

    @Resource
    private MailValidateCodeServiceImpl mailValidateCodeServiceImpl;

//    /**
//     * 登录
//     * @param user  用户信息
//     * @return  带token的集合
//     */
//    @PostMapping(value = "/login")
//    public TokenDto login(@RequestBody LoginDto user) {
//        return authService.login(user);
//    }
//
//
//    /**
//     * 获取一个临时授权
//     */
//    @PostMapping(value = "/temporaryLogin")
//    public TokenDto temporaryLogin(@RequestBody AuthService.temporaryLogin.Input input){
//        return authService.temporaryLogin(input);
//    }

    @PostMapping("/logout")
    public boolean logout() {
        String payload = RequestUtils.getJwtPayload();
        JSONObject jsonObject = JsonUtil.parseObject(payload);
        String jti = jsonObject.getString("jti"); // JWT唯一标识
        long exp = jsonObject.getLong("exp"); // JWT过期时间戳(单位:秒)
        long currentTimeSeconds = System.currentTimeMillis() / 1000;
        if (exp < currentTimeSeconds) { // token已过期
            return false;
        }
        long second = exp - currentTimeSeconds;
        redisPlugin.setEx(BaseConstant.AUTH_TOKEN_JWT_LOGOUT_KEY + jti, (int)second, "过期");
        return true;
    }


    /**
     * 获取用户信息
     *//*
    @RequestMapping(value = "/getUserInfo")
    public SysUser getUserInfo() {
        return loginService.getUserInfo();
    }*/

    /**
     * 获取用户信息
     */
    @RequestMapping(value = "/getAuthUser")
    public AuthUser getAuthUser() {
        return loginService.getAuthUser();
    }

//    /**
//     * 注册
//     */
//    @PostMapping("/register")
//    public TokenDto register(@RequestBody RegisterDto data) {
//        //注册
//        SysUser user = loginService.register(data);
//
//        //做一次授权登录
//        LoginDto loginDto = new LoginDto()
//                .setUsername(user.getUsername())
//                .setPassword(user.getPassword());
//        return this.login(loginDto);
//    }


    /**
     * 发送忘记密码的邮件验证码
     * 目前仅用于找回密码
     */
    @RequestMapping(value = "/sendForgetPassValidateCode")
    public String sendForgetPassValidateCode(@RequestBody ValidateCodeService.sendValidateCode.Input input) {
        String target = input.getTarget();
        SysUser user = loginService.findByEmail(target);
        if(user == null){
            throw new BusinessException("账户不存在，请检查后重试！");
        }
        mailValidateCodeServiceImpl.sendValidateCode(target, VALIDATE_CODE_TYPE_FORGET_PASSWORD);
        return "验证码发送成功";
    }

    /**
     * 忘记密码
     * 忘记密码的流程主要通过邮件或者手机号发送验证码，然后然后输入验证码修改密码
     */
    @RequestMapping(value = "/forgetPassword")
    public AuthService.forgetPassword.Output forgetPassword(@RequestBody AuthService.forgetPassword.Input input) {
        return authService.forgetPassword(input);
    }


    /**修改密码*/
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    public BaseResult<Boolean> modifyPassword(@RequestBody ModifyPassDto data) {
        return loginService.modifyPassword(data);
    }

}
